<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="150px" status-icon
      hide-required-asterisk="false">
      <el-form-item label="食物名称" prop="foodName">
        <el-input v-model="ruleForm.foodName" placeholder="请输入食物名称"></el-input>
      </el-form-item>
      <el-form-item label="蛋白质(g)" prop="protein">
        <el-input v-model="ruleForm.protein" placeholder="请输入蛋白质" type="number" min="0"></el-input>
      </el-form-item>
      <el-form-item label="脂肪(g)" prop="fat">
        <el-input v-model="ruleForm.fat" placeholder="请输入脂肪" type="number" min="0"></el-input>
      </el-form-item>
      <el-form-item label="碳水(g)" prop="carbohydrate">
        <el-input v-model="ruleForm.carbohydrate" placeholder="请输入碳水" type="number" min="0"></el-input>
      </el-form-item>
      <el-form-item label="热量(千卡)">
        <el-input v-model="ruleForm.caloric" placeholder="请输入热量" type="number" min="0"></el-input>
      </el-form-item>
      <el-form-item label="不溶性膳食纤维(g)" prop="fiber">
        <el-input v-model="ruleForm.fiber" placeholder="请输入不溶性膳食纤维" type="number" min="0" />
      </el-form-item>
      <el-form-item label="胆固醇(mg)" prop="cholesterol">
        <el-input v-model="ruleForm.cholesterol" type="number" placeholder="请输入胆固醇" min="0" />
      </el-form-item>
      <el-form-item label="维生素A(ugRAE)" prop="vitamina">
        <el-input v-model="ruleForm.vitamina" type="number" placeholder="请输入维生素A" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="维生素C(mg)" prop="vitaminc">
        <el-input v-model="ruleForm.vitaminc" type="number" placeholder="请输入维生素C" min="0" />
      </el-form-item>
      <el-form-item label="钙(mg)" prop="calcium">
        <el-input v-model="ruleForm.calcium" type="number" placeholder="请输入钙" min="0" />
      </el-form-item>
      <el-form-item label="钾(mg)" prop="potassium">
        <el-input v-model="ruleForm.potassium" type="number" placeholder="请输入钾" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="钠(mg)" prop="sodium">
        <el-input v-model="ruleForm.sodium" type="number" placeholder="请输入钠" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="血糖生成指数" prop="givalue">
        <!-- <el-input v-model="ruleForm.givalue" maxlength="300" placeholder="请输入血糖生成指数" size="mini" type="number"
                  min="0" /> -->
        <el-input v-model="ruleForm.givalue" type="number" placeholder="请输入血糖生成指数" min="0" size="mini" />
      </el-form-item>
      <el-form-item label="食物分类" prop="type">
        <el-select v-model="ruleForm.type" placeholder="食物分类" class="handle-select mr10">
          <span>
            <el-option key="0" label="暂无" value="0"></el-option>
          </span>
          <el-option :label="item.name" :value="item.id" v-for="item in categoryList" :key="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="食物状态" prop="unit">
        <el-radio-group v-model="ruleForm.unit">
          <el-radio :label="0" value="0">固体</el-radio>
          <el-radio :label="1" value="1">液体</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="食物描述" prop="desc">
        <el-input v-model="ruleForm.desc" placeholder="请输入食物描述" type="textarea" rows="6" maxlength="300"
          :show-word-limit="true"></el-input>
      </el-form-item>
      <el-form-item label="选择图片" height="40">
        <el-upload action="#" :multiple="false" accept=".jpg,.jpeg,.png" :show-file-list="true" list-type="picture-card"
          @change="handelFileChange" :auto-upload="false">
          <el-image class="avatar" v-if="imageUrl" :src="imageUrl" />
          <el-icon v-else>
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">jpg/png格式图片且图片大小不能超过500kb</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <span class="dialog-footer">
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      <el-button @click="handleReturn">取消</el-button>
    </span>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
export default {
  components: {},
  setup() {
    const router = useRouter()

    const checkValidator = (rule, value, callback) => {
      if (value > 5000) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    const checkCaloric = (rule, value, callback) => {
      if (value > 5000) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    const rules = reactive({
      foodName: [
        {
          required: true,
          message: '请输入食物名称',
          trigger: 'blur',
        },
      ],
      protein: [
        {
          required: true,
          message: '请输入蛋白质',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的蛋白质含量(0~100)',
        }, */,
      ],
      fat: [
        {
          required: true,
          message: '请输入脂肪',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的脂肪含量(0~100)',
        }, */,
      ],
      carbohydrate: [
        {
          required: true,
          message: '请输入碳水',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的碳水含量(0~100)',
        }, */,
      ],
      caloric: [
        {
          required: true,
          message: '请输入热量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkCaloric,
          message: '请输入正确的热量(0~10000)',
        }, */,
      ],
      fiber: [
        {
          required: false,
          message: '请输入不溶性膳食纤维含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的不溶性膳食纤维含量(0~100)',
        }, */,
      ],
      cholesterol: [
        {
          required: false,
          message: '请输入胆固醇含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的胆固醇含量(0~100)',
        }, */,
      ],
      vitamina: [
        {
          required: false,
          message: '请输入维生素A含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的维生素A含量(0~100)',
        }, */,
      ],
      vitaminc: [
        {
          required: false,
          message: '请输入维生素C含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的维生素C含量(0~100)',
        }, */,
      ],
      calcium: [
        {
          required: false,
          message: '请输入钙含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的钙含量(0~100)',
        }, */,
      ],
      potassium: [
        {
          required: false,
          message: '请输入钾含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的钾含量(0~100)',
        }, */,
      ],
      sodium: [
        {
          required: false,
          message: '请输入钠含量',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的钠含量(0~100)',
        }, */,
      ],
      givalue: [
        {
          required: false,
          message: '请输入食物血糖生成指数',
          trigger: 'blur',
        } /* ,
        {
          validator: checkValidator,
          message: '请输入正确的食物血糖生成指数(0~100)',
        }, */,
      ],
      type: [
        {
          required: true,
          message: '请选择食物类型',
          trigger: 'change',
        },
      ],
    })
    const categoryList = [
      { id: 0, name: '其他' },
      { id: 1, name: '谷类及制品' },
      { id: 2, name: '薯类、淀粉及制品' },
      { id: 3, name: '干豆类及制品' },
      { id: 4, name: '蔬菜类及制品' },
      { id: 5, name: '菌藻类' },
      { id: 6, name: '水果类及制品' },
      { id: 7, name: '坚果、种子类' },
      { id: 8, name: '植物油' },
      { id: 9, name: '畜肉类及制品' },
      { id: 10, name: '禽肉类及制品' },
      { id: 11, name: '乳类及制品' },
      { id: 12, name: '蛋类及制品' },
      { id: 13, name: '鱼虾蟹贝类' },
      { id: 14, name: '油脂' },
      { id: 15, name: '婴幼儿食品' },
      { id: 16, name: '小吃、甜饼' },
      { id: 17, name: '速食食品' },
      { id: 18, name: '饮料类' },
      { id: 19, name: '含酒精饮料' },
      { id: 20, name: '糖、果脯和蜜饯、蜂蜜类' },
      { id: 21, name: '调味品类' },
    ]
    const ruleFormRef = ref({})
    const ruleForm = ref({
      foodName: '',
      type: 3,
      unit: 0,
      fiber: 0,
      cholesterol: 0,
      vitamina: 0,
      vitaminc: 0,
      calcium: 0,
      potassium: 0,
      sodium: 0,
      givalue: '',
    })
    const selectedFile = ref(null)

    // 重置表单
    const resetForm = (formEl) => {
      imageUrl.value = ''
      formEl.resetFields()
    }

    // 获取文件数据
    const imageUrl = ref('')
    const handelFileChange = (file) => {
      const isLt500k = file.raw.size / 1024 < 500
      if (!isLt500k) {
        ElNotification({
          title: '图片过大',
          message: '图片不能超过500k',
        })
        return
      }
      selectedFile.value = file.raw

      imageUrl.value = URL.createObjectURL(file.raw)
    }
    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      formData.append('foodName', ruleForm.value.foodName)
      formData.append('protein', Number(ruleForm.value.protein))
      formData.append('fat', Number(ruleForm.value.fat))
      formData.append('carbohydrate', Number(ruleForm.value.carbohydrate))
      formData.append('caloric', Number(ruleForm.value.caloric))
      formData.append('type', ruleForm.value.type)
      formData.append('unit', ruleForm.value.unit)
      formData.append('fiber', ruleForm.value.fiber)
      formData.append('cholesterol', ruleForm.value.cholesterol)
      formData.append('vitamina', ruleForm.value.vitamina)
      formData.append('vitaminc', ruleForm.value.vitaminc)
      formData.append('calcium', ruleForm.value.calcium)
      formData.append('potassium', ruleForm.value.potassium)
      formData.append('sodium', ruleForm.value.sodium)
      formData.append('givalue', ruleForm.value.givalue)
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      }
      if (ruleForm.value.desc) {
        formData.append('desc', ruleForm.value.desc)
      }

      return formData
    }

    const formData = ref(null)
    // 提交表单
    const submitForm = async (ruleFormRef) => {
      formData.value = processFormData()
      if (!selectedFile.value) {
        ElNotification({
          title: '添加失败',
          message: '请添加封面图',
        })
        return
      }
      if (!ruleFormRef) return
      await ruleFormRef.validate((valid, fields) => {
        if (valid) {
          request
            .request({
              url: '/food/add',
              method: 'post',
              data: formData.value
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '提交成功',
                  message: '成功提交食物信息',
                })
                router.push('/foodTable')
              } else {
                ElNotification({
                  title: '更新失败',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              console.log(e)
              ElNotification({
                title: '更新失败',
                message: '请联系管理员检查失败原因',
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }

    const handleReturn = () => {
      router.push('/foodTable')
    }
    return {
      ruleForm,
      ruleFormRef,
      rules,
      handelFileChange,
      submitForm,
      resetForm,
      imageUrl,
      categoryList,
      handleReturn,
    }
  },
}
</script>

<style lang="scss" scoped></style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}

.avatar{
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
